package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.Username;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 移动端发送验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sengMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码为：{}", code);
            //使用阿里云短信服务向该手机号发送验证码
            String myPhone = new String("13224865314");
            //String myPhone = new String("18366764346");
            SMSUtils.sendMessage("瑞吉外卖", "SMS_461790102", myPhone, code);

            //保存验证码到session中
            //session.setAttribute(phone, code);

            //用redis保存短信验证码
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            return R.success("短信验证码发送成功");
        }
        return R.error("验证码发送失败");
    }

    /**
     * 移动端用户登录
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        log.info(map.toString());
        //获取到手机号
        String phone = map.get("phone").toString();
        //获取到验证码
        String code = map.get("code").toString();
        //从session中获取验证码
        //String codeInSession = session.getAttribute(phone).toString();

        //从redis中获取验证码
        String codeInSession = (String)redisTemplate.opsForValue().get(phone);

        //进行验证码对比（将session中的验证码和页面提交的验证码进行对比）
        if (codeInSession != null && codeInSession.equals(code)) {
            //如果对比相同，登录成功
            //判断是否是新用户，如果是新用户则自动注册
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);
            User user = userService.getOne(wrapper);

            if (user == null) {
                //为新用户填充信息
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                user.setName(Username.getName());

                userService.save(user);
            }
            session.setAttribute("user", user.getId());

            //登录成功即将验证码清楚
            redisTemplate.rename(phone,code);

            return R.success(user);
        }
        return R.error("登录失败");
    }

    /**
     * 移动端退出登录
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        //删除session
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}
